import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Button, Form } from 'antd';
import { router } from 'umi';
import ManageList from '@/components/ManageList';
import StandardTable from '@/components/StandardTable';
import TableButtons from '@/components/TableButtons';
import SelectForm from '@/components/SelectForm';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import RightDraw from '@/components/RightDraw';
import AddressLibDetail from './AddressLibDetail';
import FileImport from '@/components/FileImport';
import AdButton from '@/components/AdButton';
import { codes } from './utils';

@ManageList
@connect(({ addressLib, loading }) => ({
  addressLibList: addressLib.addressLibList,
  formValues: addressLib.formValues,
  loading: loading.effects['addressLib/selectAddressLibList'],
}))
@Form.create()
export default class AddressLibList extends Component {
  state = {
    selectedRows: [],
    expandForm: false,
    visible: false,
    visibleFile: false,
    detailId: '',
  };
  className = 'AddressLibList';

  componentDidMount() {
    this.selectAddressLibList();
  }

  selectAddressLibList = ({ payload = {} } = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addressLib/selectAddressLibList',
      payload,
    });
  };

  /**
   * form 查找条件 展开 收起
   */
  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.saveAllValues({ formValues: {} });
    this.selectAddressLibList();
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    const { form } = this.props;
    if (!formValues) return;
    this.saveAllValues({ formValues });
    this.selectAddressLibList({ payload: formValues });
  };

  /**
   * table 表格 批量选择
   */
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    const { formValues } = this.props;
    this.selectAddressLibList({ payload: { ...formValues, ...param } });
  };

  /**
   * table button 审核地址
   */
  checkAddress = () => {
    const { selectedRows } = this.state;
    if (selectedRows.length === 0) return;
    const { dispatch, formValues } = this.props;
    dispatch({
      type: 'addressLib/checkAddress',
      payload: { ids: selectedRows.map(v => v.id) },
      callback: data => {
        if (!data) return;
        this.selectAddressLibList({ payload: formValues });
      },
    });
  };

  /**
   * table button 新增
   */
  handleAdd = () => {
    router.push('/roadNetwork/AddressLibList/AddressLibAdd');
  };

  /**
   * Draw 打开
   */
  showDetail = (e, detailId) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    dispatch({
      type: 'addressLib/addressLibDetail',
      payload: { id: detailId },
      callback: data => {
        if (!data) return;
        this.setState({ detailId, visible: true });
      },
    });
  };

  /**
   * Draw 关闭
   */
  closeDetail = () => {
    this.setState({ visible: false });
  };

  /**
   * Draw 编辑
   */
  handleEdit = () => {
    const { detailId } = this.state;
    router.push(`/roadNetwork/AddressLibList/AddressLibEdit/${detailId}`);
    this.closeDetail();
  };

  saveAllValues = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addressLib/allValus',
      payload,
    });
  };
  //导入
  handleImportFile = () => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile });
  };

  columns = [
    {
      title: '地址',
      dataIndex: 'address',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id)}
          text={text}
          title={text}
          code={codes.showDetail}
        />
      ),
      width: 400,
    },
    {
      title: '配送区域',
      dataIndex: 'fullParentNames',
      width: 250,
    },
    {
      title: '纬度',
      dataIndex: 'latitude',
      width: 150,
    },
    {
      title: '经度',
      dataIndex: 'longitude',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'useStatus',
      render: text => <span>{text === 'OPEN' ? '待处理' : '已确认'}</span>,
    },
  ];
  render() {
    const {
      addressLibList,
      loading,
      form: { getFieldDecorator },
      isMobile,
    } = this.props;
    const { selectedRows, expandForm, visible, detailId, visibleFile } = this.state;
    const commonParams = {
      getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="地址" code="address" {...commonParams}>
        <AntdInput />
      </AntdFormItem>
    );
    // 查询条件 参数
    const selectFormParams = {
      firstFormItem,
      form: this.props.form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    // 表格按钮 参数
    const tableButtonsParams = {
      buttons: (
        <span>
          <Button.Group>
            <AdButton
              disabled={selectedRows.length === 0}
              onClick={this.checkAddress}
              text="审核"
              code={codes.ToExamine}
            />
            <AdButton onClick={this.handleImportFile} text="导入" code={codes.import} />
          </Button.Group>
        </span>
      ),
      handleAdd: this.handleAdd,
      code: codes.add,
    };

    // 详情 参数
    const rightDrawParams = {
      isMobile,
      visible,
      title: '地址库详情',
      closeDetail: this.closeDetail,
      buttons: <AdButton onClick={this.handleEdit} type="primary" text="编辑" code={codes.edit} />,
    };

    return (
      <Fragment>
        <FileImport
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`mds/mds-address-lib/matchExcelDistrict`}
          urlCase={`attachment/地址匹配模板.xlsx`}
          // urlQuery={[{ url: `mds/mds-address-lib/selectMdsAddressLibList`, payload: {} }]}
          queryData={[this.selectAddressLibList]}
          downloadFile={{
            flag: true,
            url: `mds/mds-attachment/readFile`,
            content: `导入文件匹配地址成功，是否下载？`,
          }}
          accept=".xls,.xlsx"
        />
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={addressLibList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          scrollX={1000}
          expandForm={expandForm}
          className={this.className}
        />
        <RightDraw {...rightDrawParams}>
          <AddressLibDetail detailId={detailId} />
        </RightDraw>
      </Fragment>
    );
  }
}
